<template>
  <div class="min-h-screen h-dvh flex flex-col bg-grad text-gray-900 overflow-hidden">
    <!-- 顶部栏 -->
    <header class="safe-top sticky top-0 z-30 bg-white/70 backdrop-blur-md border-b border-gray-100">
      <div class="max-w-screen-md mx-auto px-4 py-3 flex items-center justify-between">
        <!-- 左侧占位，保持平衡 -->
        <div class="w-16"></div>

        <!-- 页面标题 -->
        <h1 class="text-xl font-extrabold tracking-tight text-gray-900 flex-1 text-center">登录</h1>

        <!-- 右侧占位，保持平衡 -->
        <div class="w-16"></div>
      </div>
    </header>

    <!-- 内容区域 -->
    <main class="flex-1 min-h-0 pb-20 safe-bottom overflow-y-auto">
      <div class="max-w-screen-md mx-auto px-4 py-8">
        <!-- Logo和欢迎语 -->
        <div class="text-center mb-8">
          <div class="w-20 h-20 mx-auto mb-4 rounded-2xl bg-gradient-to-br from-brand-500 to-indigo-600 flex items-center justify-center shadow-glass">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-10 h-10 text-white">
              <path d="M12 2a6 6 0 1 1 0 12A6 6 0 0 1 12 2Z"/>
              <path d="M3 22a9 9 0 1 1 18 0H3Z"/>
            </svg>
          </div>
          <h2 class="text-2xl font-bold text-gray-900 mb-2">欢迎回来</h2>
          <p class="text-gray-600">请登录您的账户</p>
        </div>

        <!-- 登录表单 -->
        <div class="bg-white rounded-2xl shadow-glass border border-gray-100 overflow-hidden">
          <form @submit.prevent="handleSubmit" class="p-6 space-y-6">
            <!-- 账户输入框 -->
            <div>
              <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                账户
              </label>
              <div class="relative">
                <input
                  id="username"
                  v-model="form.username"
                  type="text"
                  required
                  class="w-full px-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200 outline-none bg-gray-50/50"
                  placeholder="请输入账户"
                >
                <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-5 h-5 text-gray-400">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                  </svg>
                </div>
              </div>
            </div>

            <!-- 密码输入框 -->
            <div>
              <label for="password" class="block text-sm font-medium text-gray-700 mb-2">密码</label>
              <div class="relative">
                <input
                  id="password"
                  v-model="form.password"
                  :type="showPassword ? 'text' : 'password'"
                  required
                  class="w-full px-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200 outline-none bg-gray-50/50"
                  placeholder="请输入密码"
                >
                <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                  <button
                    type="button"
                    @click="showPassword = !showPassword"
                    class="text-gray-400 hover:text-gray-600 transition-colors"
                  >
                    <svg v-if="showPassword" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5">
                      <path d="M12 15a3 3 0 100-6 3 3 0 000 6z"/>
                      <path fill-rule="evenodd" d="M1.323 11.447C2.811 6.976 7.028 3.75 12.001 3.75c4.97 0 9.185 3.223 10.675 7.69.12.362.12.752 0 1.113-1.487 4.471-5.705 7.697-10.677 7.697-4.97 0-9.186-3.223-10.675-7.69a1.762 1.762 0 010-1.113zM17.25 12a5.25 5.25 0 11-10.5 0 5.25 5.25 0 0110.5 0z" clip-rule="evenodd"/>
                    </svg>
                    <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5">
                      <path d="M3.53 2.47a.75.75 0 00-1.06 1.06l18 18a.75.75 0 101.06-1.06l-18-18zM22.676 12.553a11.249 11.249 0 01-2.631 4.31l-3.099-3.099a5.25 5.25 0 00-6.71-6.71L7.759 4.577a11.217 11.217 0 014.242-.827c4.97 0 9.185 3.223 10.675 7.69.12.362.12.752 0 1.113z"/>
                      <path d="M15.75 12c0 .18-.013.357-.037.53l-4.244-4.243A3.75 3.75 0 0115.75 12zM12.53 15.713l-4.243-4.244a3.75 3.75 0 004.243 4.243z"/>
                      <path d="M6.75 12c0-.619.107-1.213.304-1.764l-3.1-3.1a11.25 11.25 0 00-2.63 4.31c-.12.362-.12.752 0 1.114 1.489 4.467 5.704 7.69 10.675 7.69 1.5 0 2.933-.294 4.242-.827l-2.477-2.477A5.25 5.25 0 016.75 12z"/>
                    </svg>
                  </button>
                </div>
              </div>
            </div>

            <!-- 登录按钮 -->
            <button
              type="submit"
              :disabled="loading"
              class="w-full py-3.5 bg-gradient-to-r from-brand-500 to-indigo-600 text-white font-semibold rounded-xl shadow-md hover:shadow-lg transform hover:scale-[1.02] transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span v-if="!loading">登录</span>
              <span v-else class="flex items-center justify-center">
                <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                登录中...
              </span>
            </button>
          </form>
        </div>
      </div>
    </main>

    <!-- 弹框提示 -->
    <transition
      enter-active-class="transition-opacity duration-300"
      enter-from-class="opacity-0"
      enter-to-class="opacity-100"
      leave-active-class="transition-opacity duration-300"
      leave-from-class="opacity-100"
      leave-to-class="opacity-0"
    >
      <div
        v-if="showAlert"
        class="fixed inset-0 z-50 flex items-center justify-center p-4"
      >
        <!-- 背景遮罩层 - 只在错误时允许点击关闭 -->
        <div
          class="absolute inset-0 bg-black/30"
          @click="alertType === 'error' ? showAlert = false : null"
        ></div>

        <div class="relative bg-white rounded-2xl shadow-glass border border-gray-100 p-6 max-w-sm w-full mx-4">
          <!-- 图标 -->
          <div class="flex items-center justify-center w-12 h-12 mx-auto mb-4 rounded-full" :class="alertType === 'success' ? 'bg-green-50' : 'bg-red-50'">
            <svg v-if="alertType === 'success'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-green-500">
              <path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clip-rule="evenodd" />
            </svg>
            <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-red-500">
              <path fill-rule="evenodd" d="M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z" clip-rule="evenodd" />
            </svg>
          </div>

          <!-- 提示内容 -->
          <div class="text-center">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">{{ alertType === 'success' ? '成功' : '提示' }}</h3>
            <p class="text-gray-600">{{ alertMessage }}</p>
          </div>

          <!-- 确认按钮 - 只在错误时显示 -->
          <div v-if="alertType === 'error'" class="mt-6">
            <button
              @click="showAlert = false"
              class="w-full py-2.5 text-white font-medium rounded-xl transition-colors bg-brand-500 hover:bg-brand-600"
            >
              确定
            </button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { login, isLoggedIn } from '../api/auth.js'
import { getDictionary } from '../api/dictionary.js'
import { clearDictionaryCache } from '../utils/dictionary.js'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const showPassword = ref(false)
const showAlert = ref(false)
const alertMessage = ref('')
const alertType = ref('error') // 'success' 或 'error'

const form = reactive({
  username: '',
  password: ''
})

// 显示弹框
const showAlertMessage = (message, type = 'error') => {
  alertMessage.value = message
  alertType.value = type
  showAlert.value = true

  // 只在成功时1秒后自动关闭
  if (type === 'success') {
    setTimeout(() => {
      showAlert.value = false
    }, 1000)
  }
  // 错误时不自动关闭，需要用户点击确认
}

// 验证表单
const validateForm = () => {
  if (!form.username.trim()) {
    showAlertMessage('请输入账户')
    return false
  }

  if (!form.password.trim()) {
    showAlertMessage('请输入密码')
    return false
  }

  return true
}

// 处理表单提交
const handleSubmit = async () => {
  if (loading.value) return

  // 验证表单
  if (!validateForm()) {
    return
  }

  loading.value = true

  try {
    console.log('开始登录，账号:', form.username)

    // 调用真实登录接口
    const result = await login(form.username, form.password)

    console.log('登录接口返回结果:', result)
    console.log('当前登录状态:', isLoggedIn.value)

    if (result.success) {
      // 登录成功，显示成功提示
      showAlertMessage('登录成功', 'success')

      console.log('登录成功，准备刷新字典数据...')
      
      // 清除旧的字典缓存
      clearDictionaryCache()
      
      // 刷新字典数据
      try {
        console.log('开始获取最新字典数据...')
        const dictResult = await getDictionary()
        console.log('字典API返回结果:', dictResult)
        
        if (dictResult.success) {
          // 将字典数据保存到本地存储
          const dictData = dictResult.data || {}
          console.log('字典数据内容:', dictData)
          console.log('字典数据结构:', Object.keys(dictData))
          
          localStorage.setItem('h5_dictionary', JSON.stringify(dictData))
          console.log('字典数据刷新成功，已保存到localStorage')
          
          // 立即验证存储是否成功
          const storedDict = localStorage.getItem('h5_dictionary')
          console.log('验证存储结果:', storedDict ? '存储成功' : '存储失败')
          if (storedDict) {
            console.log('存储的字典数据:', JSON.parse(storedDict))
          }
        } else {
          console.warn('字典数据刷新失败:', dictResult.message)
        }
      } catch (dictError) {
        console.error('刷新字典数据异常:', dictError)
      }

      console.log('准备跳转到首页...')
      console.log('当前登录状态:', isLoggedIn.value)

      // 检查当前页面的cookie
      console.log('当前页面cookie:', document.cookie)

      // 立即跳转到首页
      console.log('执行跳转到首页...')
      router.replace('/home')
      console.log('跳转指令已执行，目标：/home')
    } else {
      // 登录失败
      console.log('登录失败，错误信息:', result.message)
      showAlertMessage(result.message || '登录失败')
    }
  } catch (error) {
    console.error('登录请求异常:', error)
    showAlertMessage('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 自定义滚动条样式 */
main::-webkit-scrollbar {
  width: 4px;
}

main::-webkit-scrollbar-track {
  background: transparent;
}

main::-webkit-scrollbar-thumb {
  background: rgba(156, 163, 175, 0.5);
  border-radius: 2px;
}

main::-webkit-scrollbar-thumb:hover {
  background: rgba(156, 163, 175, 0.7);
}

/* 输入框聚焦动画 */
input:focus {
  box-shadow: 0 0 0 3px rgba(47, 111, 248, 0.1);
}

/* 按钮悬停效果 */
button:not(:disabled):hover {
  transform: translateY(-1px);
}
</style>
